# app.py
from flask import Flask, request, render_template, redirect, url_for
import pymysql

app = Flask(__name__,template_folder='templates')

# 数据库配置
DB_CONFIG = {
    'host': 'localhost',
    'user': 'root',  # 替换为实际的MySQL用户名
    'password': '123456',  # 替换为实际的MySQL密码
    'database': 'liuyifan',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}

def get_db_connection():
    connection = pymysql.connect(**DB_CONFIG)
    return connection

@app.route('/')
def index():
    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            sql = "SELECT * FROM diary_entries ORDER BY created_at DESC"
            cursor.execute(sql)
            entries = cursor.fetchall()
        return render_template('index.html', entries=entries)
    finally:
        connection.close()

@app.route('/submit', methods=['POST'])
def submit():
    date = request.form['date']
    weather = request.form['weather']
    mood = request.form['mood']
    event = request.form['event']

    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO diary_entries (date, weather, mood, event) VALUES (%s, %s, %s, %s)"
            cursor.execute(sql, (date, weather, mood, event))
            connection.commit()
        return redirect(url_for('index'))
    finally:
        connection.close()

if __name__ == '__main__':
    app.run(host='0.0.0.0',debug=True)